package com.tz;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * Created by Administrator on 2016/7/26.
 */
@ComponentScan
@Configuration
@EnableAspectJAutoProxy //启用面向切面编程
@EnableTransactionManagement //启用声明式事务
public class AppConfig {

    @Bean(name="myDataSource")
    public DataSource dataSource(){

        BasicDataSource ds = new BasicDataSource();
        ds.setPassword("");
        ds.setUsername("sa");
        ds.setUrl("jdbc:h2:tcp://localhost/~/test");
        ds.setDriverClassName("org.h2.Driver");
        return ds;
    }

    @Bean
    public LocalSessionFactoryBean lsfb(){
        LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
        lsfb.setDataSource(dataSource());
        Properties props = new Properties();
        props.setProperty("hibernate.dialect","org.hibernate.dialect.H2Dialect");
        props.setProperty("hibernate.show_sql","true");
        lsfb.setHibernateProperties(props);
        lsfb.setPackagesToScan("com.tz.entity");
        return lsfb;
    }

    @Bean
    public HibernateTransactionManager Htm(){
        HibernateTransactionManager htm =
                new HibernateTransactionManager();
        htm.setSessionFactory(lsfb().getObject()); //手动解封装
        return htm;
    }
}
